<template>
  <a-card class="general-card" title="验证码设置" :bordered="false">
    <a-row style="margin-bottom: 16px">
      <a-radio-group v-model="type" type="button">
        <a-radio value="RESOURCE">图片源</a-radio>
        <a-radio value="SLIDER">滑块源</a-radio>
      </a-radio-group>
    </a-row>
    <a-row style="margin-bottom: 16px">
      <a-col :span="16" style="margin-bottom: 10px">
        <a-space>
          <a-button type="primary" @click="handleAdd(type)">
            添加
          </a-button>
        </a-space>
      </a-col>
      <PickTablePage
        ref="tablePageRef"
        :columns="columnsTable"
        :methods="sortMethods"
        :api="verificationPage"
        :api-params="params"
        @delete="handleDelete"
        @update="handleEdit"
        :bordered="true"
      >
        <template #resource="{ data }">
          <!-- {{ unixToDate(record) }} -->
          <a-image width="50" height="50" :src="data.resource" />
        </template>
      </PickTablePage>
    </a-row>
    <!-- 添加/编辑modal -->
    <a-modal
      v-model:visible="sliderData.enableAddModal"
      :align-center="false"
      :footer="false"
    >
      <template #title> {{ modalTitle }} </template>
      <a-form ref="formRef" :model="sliderData.form" @submit="handleAddOk">
        <a-form-item
          field="name"
          label="名称"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="sliderData.form.name" />
        </a-form-item>
        <a-form-item
          field="resource"
          label="图片"
          :rules="[REQUIRED]"
          :validate-trigger="['change']"
          validate-phone
        >
          <a-input v-model="sliderData.form.resource" />
          <a-tooltip>
            <a-button v-if="sliderData.form.resource"><icon-eye  /></a-button>
            <template #content>
              <div>
                <img
                  :src="sliderData.form.resource"
                  alt="该资源不存在"
                  style="width: 100%; margin: 0 auto"
                />
                <a
                  style="margin-top: 5px; text-align: right; cursor: pointer"
                  @click="viewImage = true"
                  >查看大图</a
                >
              </div>
            </template>
          </a-tooltip>
          <a-button type="primary" @click="handlerUpload">上传图片</a-button>
        </a-form-item>
        <a-form-item field="type" label="类型">
          <div w-full>
            <div>
              <a-radio-group v-model="sliderData.form.type" type="button">
                <a-radio value="RESOURCE">图片源</a-radio>
                <a-radio value="SLIDER">滑块源</a-radio>
              </a-radio-group>
            </div>
            <div mt-10px>
              <a-alert v-if="sliderData.form.type === 'RESOURCE'">图片源建议尺寸： 300*150 </a-alert>
              <a-alert v-if="sliderData.form.type === 'SLIDER'">上传图片为PNG格式，滑块源上传的图片尺寸不得超过任何图片源的最小尺寸。</a-alert>
            </div>
        </div>
        </a-form-item>
        <a-form-item label="操作">
          <a-button :loading="sliderData.formLoading" html-type="submit"
          type="primary">保存</a-button
          >
        </a-form-item>
      </a-form>
    </a-modal>
    <!--<a-modal v-model:visible="ossvisible" :width="1100">-->
      <!--<ossManage :close-model="handleOssOk" @changOssImage="changOssImage"></ossManage>-->
    <!--</a-modal>-->
    <a-modal v-model:visible="showOssManager" :width="1100"  @ok="handleOss" title="oss资源管理" @cancel="showOssManager = false">
      <ossManages @selected="changOssImage" :isSingle="true"></ossManages>
    </a-modal>


    <a-modal
      v-model:visible="viewImage"
      :width="1100"
      title="查看图片"
      @ok="handleOssOk"
      @cancel="handleOssCancel"
    >
      <img
        :src="sliderData.form.resource"
        alt="该资源不存在"
        style="width: 100%; margin: 0 auto; display: block"
      />
      <template #footer>
        <div style="text-align: right">
          <a-button type="text" @click="viewImage = false">关闭</a-button>
        </div>
      </template>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import { PickTablePage } from '@pickmall/ui-v3-components'  
  import { MethodsRule, ColumnsDataRule } from '@/types/global';
  import {
    verificationPage,
    delVerification,
    addVerification,
    editVerification,
  } from '@/api/setting';
  import { REQUIRED, VARCHAR20 } from '@/utils/validator';
  import { ref, watch, reactive } from 'vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import ossManage from '@/views/setting/oss-manage/index.vue';
  import ossManages from '@/components/oss-manage/index.vue';

  const type = ref<string>('RESOURCE');
  const viewImage = ref<boolean>(false);
  const ossvisible = ref<boolean>(false);
  const showOssManager = ref<boolean>(false); // oss弹框
  const selectedSku = ref(); // 选择的sku
  const formRef = ref<FormInstance>();
  interface formInterface {
    enableAddModal: boolean;
    formLoading: boolean;
    fid: string | number;
    form: {
      name: string;
      resource: string;
      type: string;
      [key: string]: any;
    };
    [key: string]: any;
  }
  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const tablePageRef = ref<any>();
  const modalTitle = ref<string>('');
  const columnsTable: ColumnsDataRule[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '图片',
      dataIndex: 'resource',
      slot: true,
      slotTemplate: 'resource',
    },

    {
      title: '创建人',
      dataIndex: 'createBy',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '最后修改人',
      dataIndex: 'updateBy',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 250,
    methods: [
      {
        title: '编辑',
        callback: 'update',
        type:'text',
        status:'warning'
      },
      {
        title: '删除',
        callback: 'delete',
        type:'text',
        status:'danger'
      },
    ],
  };

  const params = reactive({
    type,
    order: 'desc',
  });
  watch(type, (val) => {
    params.type = val;
    tablePageRef.value.init();
  });
  // 数据集
  const sliderData = reactive<formInterface>({
    enableAddModal: false,
    formLoading: false,
    fid: '', // 当前form的ids
    form: {
      name: '',
      resource: '',
      type: 'RESOURCE',
    }, // 表单提交数据
  });
  // 点击添加
  function handleAdd(type: string) {
    modalTitle.value = '添加';
    sliderData.enableAddModal = true;
    sliderData.form.name = '';
    sliderData.fid = '';
    sliderData.form.type = type;
    sliderData.form.resource = ''
  }
  // 点击修改
  function handleEdit(val: any) {
    modalTitle.value = '编辑';
    if (val) {
      Object.keys(val.record).forEach((key) => {
        // eslint-disable-next-line no-unused-expressions,no-prototype-builtins
        sliderData.form.hasOwnProperty(key)
          ? (sliderData.form[key] = val.record[key])
          : '';
      });
      sliderData.fid = val.record.id;
      sliderData.form.id = val.record.id;
      sliderData.enableAddModal = true;
    }
  }
  // 添加/修改地址
  async function handleAddOk() {
    const auth = await formRef.value?.validate();
    if (!auth) {
      let res;
      !sliderData.fid
        ? (res = await addVerification(sliderData.form))
        : (res = await editVerification(sliderData.fid, sliderData.form));
      if (res.data.success) {
        Message.success(`${sliderData.fid ? '修改' : '添加'}成功!`);
        sliderData.enableAddModal = false;
        tablePageRef.value.init();
      }
    }
  }
  // 回调删除
  function handleDelete(data: any) {
    modal.confirm({
      title: '确认删除',
      content: '确认要删除此验证码源',
      alignCenter: false,
      onOk: async () => {
        const res = await delVerification(data.record.id);
        if (res.data.success) {
          Message.success('删除成功！');
          tablePageRef.value.init();
        }
      },
    });
  }
  // 图片 url
  // const changOssImage = (e: any) => {
  //   sliderData.form.resource = e;
  // };
  // 关闭oss弹框
  const handleOssOk = (e: any) => {
    // ossvisible.value = false;
    showOssManager.value = false;
  };
  const handleOssCancel = (e: any) => {
    // ossvisible.value = false;
    showOssManager.value = false;
  };
  // 上传图片
  const handlerUpload = () => {
    // ossvisible.value = true;
    showOssManager.value = true;
  };
  // oss资源确定
  const handleOss = () => {
    showOssManager.value = false;
    sliderData.form.resource = selectedSku.value[selectedSku.value.length-1].url;
  };
  // oss资源改变
  const changOssImage = (val: any) => {
    selectedSku.value = [];
    val.forEach((item: any)=>{
      selectedSku.value.push({url:item.url})
    })
  };
</script>
